/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null){
            return null;
        }
        //第一种，pq就是root
        if(root == q || root == p){
            return root;
        }
        //第二三种,左右找,并接受
        TreeNode leftTree = lowestCommonAncestor(root.left, p, q);
        TreeNode rightTree = lowestCommonAncestor(root.right, p, q);
        //左右都有，就root  ，一边有就直接是leftTree/rightTree， 两遍都没有 这个根里没有
        if(leftTree != null && rightTree != null){
            return root;
        }else if(leftTree != null){
            return leftTree;
        }else if(rightTree != null){
            return rightTree;
        }else{
            return null;
        }
    }
}